package com.longkier.gx_library_springboot.Service;

import com.longkier.gx_library_springboot.entity.Book;
import com.longkier.gx_library_springboot.entity.BooksBorrow;
import com.longkier.gx_library_springboot.entity.User;
import com.longkier.gx_library_springboot.repository.BookRepository;
import com.longkier.gx_library_springboot.repository.BooksBorrowRepository;
import com.longkier.gx_library_springboot.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.*;
import java.util.*;

@Service
@RequiredArgsConstructor
public class BooksBorrowService {

    //private static final Logger logger = LoggerFactory.getLogger(BooksBorrowService.class);
    private final BooksBorrowRepository booksBorrowRepository;
    private final BookRepository bookRepository;
    private final UserRepository userRepository;

    /**
     * 借阅图书
     *
     * @param booksBorrow 图书借阅信息
     */
    public void borrowBook(@NotNull BooksBorrow booksBorrow) {
        // 校验借阅卡号是否存在
        String cardNumber = booksBorrow.getCardNumber();
        Optional<User> optionalUser = userRepository.findByCardNumber(cardNumber);
        if (optionalUser.isEmpty()) {
            throw new IllegalArgumentException("借阅卡号不存在");
        }
        String bookNumber = booksBorrow.getBookNumber();
        Optional<Book> optionalBook = bookRepository.findByBookNumber(bookNumber);
        optionalBook.ifPresent(book -> {
            if ("可借".equals(book.getBookStatus())) {
                book.setBookStatus("已借出");
                bookRepository.save(book);
            } else {
                throw new IllegalArgumentException("图书状态不可借");
            }
        });
        booksBorrow.setBorrowing(1);
        booksBorrow.setProcessing(0);
        booksBorrow.setBorrowDate(LocalDateTime.now());
        booksBorrow.setCloseDate(LocalDateTime.now().plusDays(15));
        booksBorrow.setCreateTime(LocalDateTime.now());
        booksBorrow.setUpdateTime(LocalDateTime.now());
        booksBorrowRepository.save(booksBorrow);
    }

    /**
     * 根据借阅卡号查询借阅信息
     *
     * @param CardNumber 借阅卡号
     * @return 借阅信息
     */
    public List<BooksBorrow> getBorrowInfo(String CardNumber) {
        return booksBorrowRepository.findByCardNumber(CardNumber);
    }

    /**
     * 续借图书
     *
     * @param borrowId 借阅ID
     * @return 是否成功
     */
    public boolean renewBook(Long borrowId) {
        BooksBorrow booksBorrow = booksBorrowRepository.findById(borrowId).orElse(null);
            if (booksBorrow != null && booksBorrow.getReturnDate() == null &&
                    LocalDateTime.now().isBefore(booksBorrow.getCloseDate())){// 判断借阅记录是否存在且未归还、借阅期限未过
                booksBorrow.setCloseDate(booksBorrow.getCloseDate().plusDays(7));
                booksBorrow.setUpdateTime(LocalDateTime.now());
                booksBorrowRepository.save(booksBorrow);
                return true;
            }
            else{
                return false;
            }
    }

    /**
     * 处理逾期借阅记录
     *
     * @param borrowId 借阅ID
     * @param violationNote 违规记录
     * @return 是否成功
     */
    public boolean handleOverdue(Long borrowId, String violationNote) {
        BooksBorrow booksBorrow = booksBorrowRepository.findById(borrowId).orElse(null);
        if (booksBorrow != null && booksBorrow.getViolationNote() == null
                && booksBorrow.getReturnDate().isAfter(booksBorrow.getCloseDate())) {
            booksBorrow.setProcessing(0);
            booksBorrow.setViolationNote(violationNote);
            booksBorrow.setUpdateTime(LocalDateTime.now());
            booksBorrowRepository.save(booksBorrow);
            //禁用逾期用户
            User user = userRepository.findByCardNumber(booksBorrow.getCardNumber()).orElse(null);
            if (user != null) {
                user.setStatus(0);
                userRepository.save(user);
            }
            return true;
        }
        return false;
    }



    /**
     * 归还图书
     *
     * @param borrowId 借阅ID
     * @return 是否成功
     */
    public boolean returnBook(Long borrowId) {
        BooksBorrow booksBorrow = booksBorrowRepository.findById(borrowId).orElse(null);
        if (booksBorrow != null && booksBorrow.getReturnDate() == null) {
            if(LocalDateTime.now().isAfter(booksBorrow.getCloseDate())){//判断归还日期是否超期
                booksBorrow.setProcessing(1);// 设置为待处理状态
            }
            booksBorrow.setBorrowing(0);//结束借阅状态
            booksBorrow.setReturnDate(LocalDateTime.now());
            booksBorrow.setUpdateTime(LocalDateTime.now());
            booksBorrowRepository.save(booksBorrow);

            // 更新图书状态为“可借”
            String bookNumber = booksBorrow.getBookNumber();
            Optional<Book> optionalBook = bookRepository.findByBookNumber(bookNumber);
            optionalBook.ifPresent(book -> {
                book.setBookStatus("可借");
                bookRepository.save(book);
            });
            return true;
        }
        return false;
    }

    /**
     * 查询所有借阅记录
     *
     * @param page 页码
     * @param size 每页大小
     * @return 借阅记录列表
     */
    public Page<BooksBorrow> getAllBorrowedBooks(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return booksBorrowRepository.findAllByOrderByCreateTimeDesc(pageable);
    }

}
